package com.interview.javabasic.Sort;/*
@李子宁
Happy,happy everyday!
冲鸭！
*/

import cn.zeronineten.testSort;

import java.util.Arrays;

public class QuickSort {
    public static void main(String[] args) {
        int arr[] = {2,8,5,4,9,6,3,5,8,4,7,11};
        quick(arr,0,arr.length-1);
        for (int i : arr) {
            System.out.println(i);
        }

    }
    public static void quickSort(int arr[],int left,int right){
        int l = left;
        int r = right;
        int pivot = arr[(left + right)/2];
        int tmp = 0;//用来交换
        //循环的目的是让pivot，比他小的放左边，比他大的放右边
        while (l<r){
            //在pivot一直找，找到比比pivot
            while (arr[l] < pivot){
                l ++;
            }
            while (arr[r] > pivot){
                r --;
            }
            //证明第一轮排序结束了，左边小，右边大
            if (l >=r){
                break;
            }
            tmp = arr[l];
            arr[l] = arr[r];
            arr[r] = tmp;

            //如果交换完后发现
            if (arr[l] == pivot){
                r -=1;
            }
            if (arr[r] == pivot){
                l +=1;
            }
        }
        if (l==r){
            l+=1;
            r-=1;
        }
        
        //向左递归
        if (left < r){
            quickSort(arr,left,r);
        }
        if (right > l){
            quickSort(arr,l,right);
        }
    }

    public static void quick(int arr[],int left,int right){
        int l = left;
        int r = right;
        int pivot = arr[(left+right)/2];
        int tmp = 0;

        while (l<r){
            while (arr[l]<pivot){
                l++;
            }
            while (arr[r] > pivot){
                r--;
            }

            if (l>=r){
                break;
            }
            tmp = arr[l];
            arr[l] = arr[r];
            arr[r] = tmp;
            if (arr[l] == pivot){
                r--;
            }
            if (arr[r] == pivot){
                l++;
            }
        }
        if (l==r){
            l++;
            r--;
        }
        if (left<r){
            quick(arr,left,r);
        }
        if (right>l){
            quick(arr,l,right);
        }
    }
}
